import { observable, action, toJS } from "mobx";
import { RouteLayout } from 'weaver-mobile-page';
import { Toast, Tools } from 'weaver-mobile';
import app from '../../apis/app';
import { permissionType } from '../../components/form/permission/type';

const { SPECIFIED_USER, ANY_USER } = permissionType;
const getLabel = Tools.getLabel; 

export default class PermissionStore {
  @observable permissionValue = ANY_USER;
  @observable browsers = [];
  @observable browsersSize = 0;
  @observable recentAddList = [];
  @observable appMsg = {};
  @observable layout = '';
  @observable hasInit = true;
  @observable appid = '';
  @action init = (appid, showInTab = false) => {
    this.appid = appid;
    this.hasInit = false;

    if (showInTab) {
      this.layout = new RouteLayout.Store({ route: '/form/power', id: 'share' });
    } else {
      this.layout = new RouteLayout.Store({ route: '/form/permission',id: 'share' })
    }
    
    if (appid) {
      app.getBaseInfo(appid).then((data) => {
        this.appMsg = data;
        this.getBrowsers();
      });
    }
  }

  @action setBrowsers = (value, sendForm = false) => {
    return new Promise(resolve => {
      app.addSubmitMember({
        appid: this.appid,
        data: JSON.stringify(value),
        sendForm: sendForm
      }).then(() => {
        this.getBrowsers();
        resolve();
      })
    });
    
  };

  getBrowsers = () => {
    const appid = this.appid;

    app.getSubmitAuthInfo(appid).then(res => {
      this.permissionValue = res.type;

      if (res.type === SPECIFIED_USER) {
        this.browsers = res.user.filter(user => Boolean(user));
        this.browsersSize = res.size;
      }

      this.hasInit = true;
    })
  }

  @action changeBrowser = (id, type) => {
    app.delSubmitMember({
      appid: this.appid,
      memberType: type,
      memberId: id
    }).then(() => {
      let data = toJS(this.browsers);

      data.forEach((p, i) => {
        if (p.id === id) {
          data.splice(i, 1)
        }
      });
      this.browsers = data;
    });

    Toast.success(getLabel(523319, '删除成功'), 1);
  }

  @action changePermissionType = (e) => {
    this.permissionValue = e;

    app.submitAuthChange({
      appid: this.appid,
      submissionAuthority: e
    }).then(() => this.getBrowsers(), Toast.success(getLabel(523251, '操作成功'), 1))
  }
}





